package com.mskj.zxmy.service.serviceImpl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mskj.zxmy.common.BusinessException;
import com.mskj.zxmy.dto.ReportInfo;
import com.mskj.zxmy.dto.TaskDto;
import com.mskj.zxmy.entity.*;
import com.mskj.zxmy.mapper.MyTaskMapper;
import com.mskj.zxmy.service.MyTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: zxmy
 * @BelongsPackage: com.mskj.zxmy.service.serviceImpl
 * @Author: lk
 * @CreateTime: 2025-07-22
 * @Description: TODO
 * @Version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MyTaskServiceImpl implements MyTaskService {

    private final MyTaskMapper myTaskMapper;

    @Override
    public TaskDto queryTaskInfo(Integer orderId, Integer processId) {
        String loginId = StpUtil.getLoginId().toString(); // 当前用户
        Map<String, Object> processTask = myTaskMapper.getById(processId);
        String processName = processTask.get("processName").toString();


        Integer count = myTaskMapper.countSignInRecord(processName, loginId);
        log.info("签到记录数量: {}", count);
        
        if (count == null || count == 0) {
            log.warn("用户 {} 在工序 {} 中未签到", loginId, processName);
            throw new BusinessException("当前未签到请签到");
        }
        
        log.info("签到验证通过，返回任务信息");
        return myTaskMapper.queryTaskInfoByOPId(orderId, processId);
    }


    @Override
    public String beginProcessTask(Integer processTaskId) {
        if (ObjectUtil.isNotNull(myTaskMapper.getById(processTaskId).get("taskStartTime")))
            throw new BusinessException("该任务已开始");
        LocalDateTime now = LocalDateTime.now();
        myTaskMapper.updateStartTime(processTaskId, now);
        return now.toString();
    }

    @Override
    public ReportInfo getReportingWorks(Integer processTaskId) {
        ReportInfo reportInfo = myTaskMapper.getReportingWorksByPid(processTaskId);
        reportInfo.setBgNo(getAuseSerialNo());
        reportInfo.setReportTime(LocalDateTime.now());
        if (StringUtils.isBlank(reportInfo.getSignInStrList())) throw new BusinessException("当前工序没有找到签到人");
        reportInfo.setEmpNames(String.join(",", myTaskMapper.getNickNameByMemberIds(reportInfo.getSignInStrList())));
        return reportInfo;
    }

    private String getAuseSerialNo() {
        String now = LocalDate.now().toString().replace("-", "");
        String prefix = "BG" + now.substring(2, 4) + now.substring(4);

        String maxNo = myTaskMapper.getMaxBgSerialNumber(prefix);
        if (StringUtils.isBlank(maxNo)) {
            maxNo = prefix + "0001";
        }

        String suffix = String.format("%04d", Integer.parseInt(maxNo.substring(8)) + 1);
        return maxNo.substring(0, 8) + suffix;
    }

    @Override
    public String batchQcAction(Integer processTaskId, Integer barCodeId) {
//        BarcodeManagementTable main = myTaskMapper.getBarCode(barCodeId);
//        Map<String, Object> processTask = myTaskMapper.getById(processTaskId);
//        Object loginId = StpUtil.getLoginId();
//        if (ObjectUtil.isNotNull(loginId)) main.setModified(loginId.toString());
//        main.setValidity("有效");
//        main.setProductionTasks(Integer.parseInt(processTask.get("associatedTasks").toString()));
//        main.setProductName(Integer.parseInt(processTask.get("productInformation").toString()));
//        main.setCurrentProcessTask(processTaskId);
//        main.setModified1(new Date());
//        main.
//        myTaskMapper.updateBarcodeMain(main);
//        return main.getBatchBarCodes();
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean productReport(ReportInfo reportInfo) throws ParseException {
        String batchCode = reportInfo.getBatchCode();
        if (StringUtils.isBlank(batchCode)) throw new BusinessException("请填写批次号");

        BarcodeManagementTable main = myTaskMapper.getBarCodePoByCode(batchCode);


        Map<String, Object> processTask = myTaskMapper.getById(reportInfo.getProcessTaskId());
        String bgrs = myTaskMapper.getBgrs(processTask.get("processName").toString());
        String loginId = getLoginId();
        if (ObjectUtil.isNotNull(loginId)) main.setModified(loginId);
        main.setValidity("有效");
        main.setProductionTasks(Integer.parseInt(processTask.get("associatedTasks").toString()));
        main.setProductName(Integer.parseInt(processTask.get("productInformation").toString()));
        main.setCurrentProcessTask(reportInfo.getProcessTaskId());
        main.setModified1(new Date());
        main.setNumber(reportInfo.getReportCount());
        myTaskMapper.updateBarcodeMain(main);

        List<BarCodeManagementDetails> actionDetails = myTaskMapper.getActionDetails(main.getId());
        BarCodeManagementDetails detail = new BarCodeManagementDetails();
        detail.setBindTheProduct(Integer.parseInt(processTask.get("productInformation").toString()));
        detail.setBarCodeBehavior("绑定条码");
        detail.setNumber(reportInfo.getReportCount());
        detail.setCreated(new Date());
        detail.setSynchronisingFolderFailedSS(loginId);
        detail.setLinkBarCodeManagement(main.getId());
        detail.setLinkProcessTasks(reportInfo.getProcessTaskId());
        detail.setResponsiblePersons(bgrs);

        if (CollectionUtil.isEmpty(actionDetails)) {
            detail.setId(null);
            myTaskMapper.saveBarcodeDetail(detail);
        }
        detail.setId(null);
        detail.setBarCodeBehavior("生产报工");
        myTaskMapper.saveBarcodeDetail(detail);

        // 更新主表的number字段 - 根据子表数据计算
        updateBarcodeMainNumber(main.getId());

        ChecklistSc05 checklistSc05 = new ChecklistSc05();
        checklistSc05.setWellCallTheFactoryStreamer(reportInfo.getBgNo());
        checklistSc05.setLinkProcessTasks(reportInfo.getProcessTaskId());
        checklistSc05.setAssociatedProductionTasks(Integer.parseInt(processTask.get("associatedTasks").toString()));
        checklistSc05.setProductInformation(Integer.parseInt(processTask.get("productInformation").toString()));
        checklistSc05.setProcessName(reportInfo.getProcessName());
        checklistSc05.setDateOfReport(DateUtils.parseDate(LocalDateTime.now().toLocalDate().toString(), "yyyy-MM-dd"));
        checklistSc05.setNumberOfTasks(reportInfo.getTaskCount());
        checklistSc05.setNumberOfCompleted(reportInfo.getFinishCount());
        checklistSc05.setNumberOfReporters(reportInfo.getReportCount());
        checklistSc05.setNumberOfEndoflifeWarranties(reportInfo.getZjCount());
//        checklistSc05.setRemainingNumber(new BigDecimal("0"));
        Map<String, Object> process = myTaskMapper.getProcessByName(processTask.get("processName").toString());
        checklistSc05.setUnitPrice(((BigDecimal) process.get("unitPrice")));
//        checklistSc05.setRealWages(new BigDecimal("0"));
        checklistSc05.setAuditStatus("已审核");
        checklistSc05.setReportingStaff(loginId);
        checklistSc05.setSynchronisingFolderFailedSS(loginId);
        checklistSc05.setCreated(new Date());
        checklistSc05.setModifyer(loginId);
        checklistSc05.setModified(new Date());
//        checklistSc05.setReportTheDetails("");
        checklistSc05.setBatchOrderNumber(batchCode);

        myTaskMapper.saveReport(checklistSc05);

        if (ObjectUtil.isNotNull(process.get("repository1")) && process.get("repository1").toString().equals("1")) {
            Ck03Listing ck03Listing = new Ck03Listing();
            ck03Listing.setDocumentType("生产入库");
            ck03Listing.setRepositoryStatus("未入库");
            ck03Listing.setRepositoryNumber(getMaxRkNo());
            ck03Listing.setRepositoryDate(new Date());
            ck03Listing.setOperator(loginId);
            ck03Listing.setProductionTasks(reportInfo.getProcessTaskId());
            ck03Listing.setSingleBatch(batchCode);
            myTaskMapper.saveRkd(ck03Listing);

            Ck04ListOfEntriesListOfEntries rkDetail = new Ck04ListOfEntriesListOfEntries();
            rkDetail.setProductInformation(Integer.parseInt(processTask.get("productInformation").toString()));
            rkDetail.setBatchNumber(batchCode);
            rkDetail.setNumberOfEntries(reportInfo.getReportCount());
            rkDetail.setScantobaseStatus("未扫码");
            rkDetail.setLinkToList(ck03Listing.getId());
            myTaskMapper.saveRkDetail(rkDetail);

        }


        return Boolean.TRUE;
    }

    private static String getLoginId() {
        String loginId = null;
        try {
            loginId = StpUtil.getLoginId().toString();
        } catch (Exception e) {
            loginId = "6b94424b9c3c422780255d75437eed6a";
        }
        return loginId;
    }

    private String getMaxRkNo() {
        String now = LocalDate.now().toString().replace("-", "");
        String prefix = "RK" + now;

        String maxNo = myTaskMapper.getMaxBgSerialNumberRk(prefix);
        if (StringUtils.isBlank(maxNo)) {
            maxNo = prefix + "0001";
        }

        String suffix = String.format("%04d", Integer.parseInt(maxNo.substring(10)) + 1);
        return prefix + suffix;
    }

    /**
     * 根据子表数据更新主表的number字段
     * 逻辑：主表的数量根据最新的条码行为来赋值
     * 1. 获取最新的条码行为和产品名称
     * 2. 对相同条码行为和相同产品名称的数据求和
     * 3. 新的条码行为会覆盖主表之前的数量
     */
    private void updateBarcodeMainNumber(Integer barcodeId) {
        log.info("开始更新条码主表number字段: barcodeId={}", barcodeId);
        
        // 直接使用SQL更新，SQL中已经实现了分组求和和取最大值的逻辑
        int updateResult = myTaskMapper.updateBarcodeMainNumber(barcodeId);
        
        if (updateResult > 0) {
            log.info("条码主表number字段更新成功: barcodeId={}, updateResult={}", barcodeId, updateResult);
        } else {
            log.warn("条码主表number字段更新失败: barcodeId={}, updateResult={}", barcodeId, updateResult);
        }
    }


//    @Override
//    public CollarList llBackInfo(Integer processTaskId) {
//        Map<String, Object> processTask = myTaskMapper.getById(processTaskId);
//        Map<String, Object> prod = myTaskMapper.getProductById(processTask.get("productInformation").toString());
//        CollarList collarList = new CollarList();
//        collarList.setProcessTaskId(processTaskId);
//        collarList.setTheCollarNumber(getMaxLldNo());
//        collarList.setF775(new Date());
//        collarList.setTypeOfCollar("生产领料");
//        collarList.setProductionTasks(Integer.parseInt(processTask.get("associatedTasks").toString()));
//        collarList.setTotalNumber(((BigDecimal) processTask.get("numberOfTasks")));
//        collarList.setAssociatedProducts(Integer.parseInt(processTask.get("productInformation").toString()));
//        collarList.setTheLeadman(getLoginId());
//        Map<String, Object> productTask = myTaskMapper.getProductTask(collarList.getProductionTasks());
//        collarList.setDevNo(productTask.get("missionStream").toString());
//        collarList.setProdInfo(ObjectUtil.isNotNull(prod.get("dataTitle1")) ? prod.get("dataTitle1").toString() : prod.get("productName").toString());
//        collarList.setProcessName(processTask.get("processName").toString());
//        collarList.setLlMan(myTaskMapper.getNickNameByMemberIds(getLoginId()).get(0));
////        collarList.setCollarListDetailsList(getLldDetails(processTask, prod));
//        return collarList;
//    }
@Override
public RepositoryApplication SQCKBackInfo(Integer processTaskId) {
    Map<String, Object> processTask = myTaskMapper.getById(processTaskId);
    Map<String, Object> prod = myTaskMapper.getProductById((Integer) processTask.get("productInformation"));

    RepositoryApplication repositoryApplication = new RepositoryApplication();
    repositoryApplication.setLinkProcessTasks(processTaskId);
    repositoryApplication.setRequestingASingleNumber(getMaxLldNo());
    repositoryApplication.setDateOfApplication(new Date());
    repositoryApplication.setTypeOfApplication("领料出库");
    // associatedTasks 可能为BigDecimal或String
    Object associatedTasksObj = processTask.get("associatedTasks");
    Integer associatedTasks = null;
    if (associatedTasksObj instanceof BigDecimal) {
        associatedTasks = ((BigDecimal) associatedTasksObj).intValue();
    } else if (associatedTasksObj != null) {
        associatedTasks = Integer.parseInt(associatedTasksObj.toString());
    }
    repositoryApplication.setProductionTasks(associatedTasks);
    // numberOfTasks 可能为BigDecimal
    Object numberOfTasksObj = processTask.get("numberOfTasks");
    BigDecimal numberOfTasks = null;
    if (numberOfTasksObj instanceof BigDecimal) {
        numberOfTasks = (BigDecimal) numberOfTasksObj;
    } else if (numberOfTasksObj != null) {
        numberOfTasks = new BigDecimal(numberOfTasksObj.toString());
    }
    repositoryApplication.setNumberOfApplications(numberOfTasks);
    // productInformation 可能为BigDecimal或String
    Object productInfoObj = processTask.get("productInformation");
    Integer productInfo = null;
    if (productInfoObj instanceof BigDecimal) {
        productInfo = ((BigDecimal) productInfoObj).intValue();
    } else if (productInfoObj != null) {
        productInfo = Integer.parseInt(productInfoObj.toString());
    }
    repositoryApplication.setAssociatedProducts(productInfo);
    repositoryApplication.setApplicant(getLoginId());
    Map<String, Object> productTask = myTaskMapper.getProductTask(repositoryApplication.getProductionTasks());
    repositoryApplication.setDevNo(productTask.get("missionStream").toString());
    repositoryApplication.setProdInfo(ObjectUtil.isNotNull(prod.get("dataTitle1")) ? prod.get("dataTitle1").toString() : prod.get("productName").toString());
    repositoryApplication.setProcessName(processTask.get("processName").toString());
    repositoryApplication.setApplicant(myTaskMapper.getNickNameByMemberIds(getLoginId()).get(0));
//        collarList.setCollarListDetailsList(getLldDetails(processTask, prod));
    return repositoryApplication;
}

    private String getMaxLldNo() {
        String now = LocalDate.now().toString().replace("-", "");
        String prefix = "CKSQ" + now;

        String maxNo = myTaskMapper.getMaxLLSerialNumber(prefix);
        if (StringUtils.isBlank(maxNo)) {
            return prefix + "0001";
        }

        // 标准格式：CKSQ + 8位日期 + 4位序号 = 16位
        // 从倒数4位提取序号
        String sequencePart = maxNo.substring(maxNo.length() - 4);
        int currentSequence = Integer.parseInt(sequencePart);
        String suffix = String.format("%04d", currentSequence + 1);
        return prefix + suffix;
    }

    private List<CollarChecklist> getLldDetails(Map<String, Object> processTask, Map<String, Object> prod) {
        List<CollarChecklist> lldDetails = new ArrayList<>();
        CollarChecklist detail = new CollarChecklist();
        detail.setMaterialInformation(Integer.parseInt(prod.get("id").toString()));
        detail.setNumber(((BigDecimal) processTask.get("numberOfTasks")));
        detail.setProductNo(prod.get("productNumber").toString());
        detail.setProductGg(prod.get("productSpecifications").toString());
        detail.setProductName(prod.get("productName").toString());
        detail.setProductXh(prod.get("typeOfProduct").toString());
        detail.setEocLevel(prod.get("environmentalProtectionLevel").toString());
        detail.setLlCount(detail.getNumber());
        lldDetails.add(detail);
        return lldDetails;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Boolean lldSave(CollarList collarList) {
//        if (CollectionUtil.isEmpty(collarList.getDetailList())) throw new RuntimeException("领料单详情不能为空");
//
//        collarList.setLlState("未领料");
//        myTaskMapper.saveLLd(collarList);
//
//        List<CollarChecklist> list = collarList.getDetailList().stream().map(detail -> {
//            CollarChecklist collarChecklist = new CollarChecklist();
//            collarChecklist.setF8d0(collarList.getId());
//            collarChecklist.setMaterialInformation(detail.getId());
//            collarChecklist.setNumber(detail.getLlCount());
//            return collarChecklist;
//        }).toList();
//
//        myTaskMapper.saveLLdDetail(list);
//
//        return Boolean.TRUE;
//
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean CKSQSave(RepositoryApplication repositoryApplication) {
        if (CollectionUtil.isEmpty(repositoryApplication.getChecklistForTheCheckout())) throw new RuntimeException("领料单详情不能为空");

        Map<String, Object> processTask = myTaskMapper.getProductTask(repositoryApplication.getProductionTasks());
        repositoryApplication.setWorksheetStatus("待出库");
        repositoryApplication.setNumberOfApplications((BigDecimal) processTask.get("numberOfTasks"));
        repositoryApplication.setApplicant(StpUtil.getLoginId().toString());
        repositoryApplication.setSynchronisingFolderFailedSS(StpUtil.getLoginId().toString());
        myTaskMapper.saveLLd(repositoryApplication);

        List<ChecklistForTheCheckout> list = repositoryApplication.getChecklistForTheCheckout().stream().map(detail -> {
            ChecklistForTheCheckout checklistForTheCheckout = new ChecklistForTheCheckout();
            checklistForTheCheckout.setAssociatedApplicationList(repositoryApplication.getId());
            checklistForTheCheckout.setProductInformation(detail.getProductInformation());
            checklistForTheCheckout.setNumberOfReleases(repositoryApplication.getNumberOfApplications());
            return checklistForTheCheckout;
        }).toList();

        myTaskMapper.saveLLdDetail(list);

        return Boolean.TRUE;

    }
}
